<template>
	<view>
		<view id="app">
			<view class="container">


				<view class="group-container" v-for="(group, findex) in groups" :key="group.id">
					<!-- <view class="group-header" @click="toggleGroupCollapse(group.id)"> -->
					<view class="group-header">
						<view class="group-title">
							<u-icon name="home" size="24" color="#fff"></u-icon>
							<text> {{ group.factory ? group.factory.userNickName : '未选择工厂' }}</text>
							<!-- <text>工厂组  {{ group.id }} - {{ group.factory ? group.factory.userName : '未选择工厂' }}</text>-->
						</view>
						<view class="group-actions">

							<!-- <view>
								<u-button class="action-btn delete-btn" @click="removeGroup(group.id)">
									<u-icon name="trash" color="#fff" size="18"></u-icon>
								</u-button>
							</view>

							<view>
								<u-button class="action-btn" @click.stop="toggleGroupCollapse(group.id)">
									<u-icon :name="group.collapsed ? 'arrow-down' : 'arrow-up'" color="#fff"
										size="18"></u-icon>
								</u-button>
							</view> -->


						</view>
					</view>

					<view class="group-content" v-if="!group.collapsed">
						<view class="form-section">
							<!-- <view class="section-title">
								<u-icon name="map" size="20" color="#3498db"></u-icon>
								<text>选择工厂</text>
							</view> -->
							<u-cell-group>

								<u-cell
									:title="group.factory ? `${group.factory.userNickName} (${group.factory.jobName})` : '请选择工厂'"
									:arrow="true" @click="showFactoryPicker(group.id)">
									<u-icon slot="icon" name="home" size="24" color="#3498db"></u-icon>
								</u-cell>
							</u-cell-group>
						</view>

						<view class="form-section" v-if="group.factory">
							<view class="section-title">
								<u-icon name="list" size="20" color="#3498db"></u-icon>
								<text>选择成品及配件</text>
							</view>

							<view class="search-container">
								<u-search placeholder="搜索成品名称或配件..." @custom="(value) => filteredProducts(value,group)"
									v-model="group.searchQuery"></u-search>

							</view>
							<view class="products-container">
								<view class="empty-state" v-if="group.productList.length < 1">
									<u-icon name="search" size="48" color="#bdc3c7"></u-icon>
									<p>未找到匹配的成品或配件</p>
									<p>请尝试其他搜索关键词</p>
								</view>
								<u-checkbox-group v-model="group.productCheckboxGroup" placement="column">
									<view class="product-item" v-for="product in group.productList" :key="product.id"
										:class="{active: group.selectedProducts.includes(product.id)}">

										<view class="product-header"
											@click="toggleProductExpansion(group.id, product.id)">
											<u-checkbox v-model="group.selectedProducts" :key="product.id"
												:value="product.id" :name="product.id" shape="circle"
												@change="handleCheckboxChange(group.id, product.id)">
											</u-checkbox>
											<view class="product-info">
												<view class="product-name">
													{{ product.name }}
													<!-- <span class="product-match"
													v-if="isProductMatch(product, group.searchQuery)">
													成品匹配
												</span> -->
												</view>
												<!-- <view class="product-id">
												型号: {{ product.model }} | 库存: {{ product.stock }}
											</view> -->
											</view>
											<u-number-box v-model="product.quantity" v-if="currentUserJob !='cg'"
												:disabled=" !group.selectedProducts.includes(product.id)" integer
												bg-color="#f8fafc"
												@change="(val) => correctionProduct(val,group.id,product.id)">
												{{ product.quantity }}</u-number-box>


											<u-icon name="arrow-right" class="product-arrow" :customStyle="group.expandedProducts.includes(product.id) ?
												    'transform: rotate(90deg); transform-origin: center;' : 
												    ''" color="#95a5a6"></u-icon>
										</view>


										<u-checkbox-group v-model="group.accessoryCheckboxGroup" placement="column">
											<view class="accessories-container"
												v-if="group.expandedProducts.includes(product.id)">

												<view class="accessory-item" v-for="accessory in product.accessories"
													:key="accessory.id"
													:class="{highlight: isAccessoryMatch(accessory, group.searchQuery)}">


													<u-checkbox :key="accessory.id" :value="accessory.id"
														:name="accessory.id" shape="circle"
														@change="handleAccessoriesCheckboxChange(group.id,product.id, accessory.id)"></u-checkbox>


													<view class="accessory-info">
														<view class="accessory-name">
															{{ accessory.name }}  {{ accessory.isPartsPublic === 'Y' ? '(公共)' : '' }}
															<!-- <span class="product-match"
															v-if="isAccessoryMatch(accessory, group.searchQuery)">
															配件匹配
														</span> -->
														</view>
														<view class="accessory-spec">
															规格: {{ accessory.spec || '' }}
														</view>
														<view class="accessory-spec" v-if="currentUserJob !='cg'">
															库存: {{ accessory.stockNum }}
														</view>

														<view class="accessory-spec">
															单价: ￥{{ accessory.price   || ''}}
														</view>
													</view>
													<view class="quantity-control">
														<u-number-box v-model="accessory.quantity" :min="0" :step="1"
															:disabled="currentUserJob ==='cpc'
															||  !group.selectedAccessories.includes(accessory.id)"
															@change="(val) => correctionPurchase(val,product.id,accessory,group.id)"
															integer bg-color="#f8fafc"></u-number-box>
													</view>
												</view>
											</view>
										</u-checkbox-group>
										<view class="accessory-item"
											v-if="group.expandedProducts.includes(product.id) && (group.factory.jobId ===19 || group.factory.jobId ===18)">
											<text>加工费单价：</text>
											<u--input v-model="product.productProcessingPrice" placeholder="请输入加工费"
												type="number" border="surround" style="width:120px;"></u--input>
										</view>
									</view>
								</u-checkbox-group>
								<u-button @click="productPartsList" v-if="group.productList.length > 1">加载更多</u-button>
							</view>

						</view>
					</view>
					<view style="padding: 10px;">
						<view>
							<text>采购</text>
							<u-radio-group v-model="purchaseType" placement="row">
								<u-radio :customStyle="{marginBottom: '8px'}" v-for="(item, index) in radiolist1"
									:key="item.key" :label="item.name" :value="item.key" :name="item.name">
								</u-radio>
							</u-radio-group>
						</view>
						<view>
							<text>选择日期</text>
							<view class="date-box" @click="openDatePicker">
								{{ displayDate || '点击选择日期' }}
							</view>

							<u-datetime-picker :show="pickerVisible" mode="date" v-model="dateValue"
								@confirm="onDateConfirm" @cancel="pickerVisible = false" />

						</view>

						<!-- <view>
							<text>入库单号</text>
							<u--input placeholder="请输入入库单号" border="surround" v-model="wareNum"></u--input>
						</view> -->
						<view>
							<text>备注</text>
							<u--textarea v-model="remark" placeholder="请输入备注"></u--textarea>

						</view>

						<view>
							<text>上传单据</text>
							<u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" multiple
								:maxCount="10"></u-upload>
						</view>
						<view>
							<view class="title">签名：</view>
							<u-button type="info" @click="showCanvasPopup = true" shape="circle">
								点击输入签名
							</u-button>
							<view class="signature-container">
								<u-image v-if="sign" :src="sign" mode="widthFix" class="signature-image" alt="签名" />
							</view>
						</view>
						<view class="add-group-btn">
							<u-button type="info" @click="submitPurchase" shape="circle">
								提交
							</u-button>
						</view>
					</view>
				</view>
				<!-- 
				<view class="add-group-btn">
					<u-button type="primary" @click="addGroup" shape="circle" icon="plus-circle">
						添加工厂组
					</u-button>
				</view> -->


			</view>


			<!-- 工厂选择器 -->
			<view>
				<u-picker :show="showFactoryPickerModel" :columns="factories" @confirm="factorySelected"
					@cancel="showFactoryPickerModel = false" :closeOnClickOverlay=true
					keyName="userNickName"></u-picker>

				<my-canvas :visible.sync="showCanvasPopup" @update-value="canvasConfirmHandle" v-if="showCanvasPopup" />
			</view>
		</view>
	</view>
</template>

<script>
	import vueEsign from 'vue-esign'
	import cfg from '@/utils/config.js';
	import myCanvas from '@/pages/canvas/index.vue'
	import {
		cloneDeep
	} from 'lodash';
	var x = 20;
	var y = 20;
	export default {
		components: {
			myCanvas
		},
		onLoad() {},
		mounted() {

			this.factoryList()

			this.productPartsList()
			this.getCurrentUserJob();
		},
		onShow() {




		},
		data() {
			return {
				iconSize: 24,
				page: 1,
				rows: 10,
				status: 'loading',
				isload: true,
				showCanvasPopup: false,
				sign: '',
				fileList1: [],
				searchText: '',
				pickerVisible: false, // 控制 picker 显示
				dateValue: Number(new Date()), // 最终要提交的时间戳（ms）
				displayDate: '', // 页面上显示给用户看的完整时间字符串

				wareNum: '', //入库单号
				remark: '', //备注
				currentUserJob: '',
				showFactoryPickerModel: false,
				currentGroupId: null,
				groups: [{
					id: 1,
					//工厂
					factoryId: null,
					factory: null,
					searchQuery: '',
					productList: [],
					expandedProducts: [],
					productCheckboxGroup: [],
					accessoryCheckboxGroup: [],
					//选中的配件
					selectedAccessories: [],
					//选中的成品
					selectedProducts: [],
					selectedAccessoriesSave: [],
					selectedProductsSave: [],
					collapsed: false
				}],
				accessoriesLoadList: {},
				factories: [],
				products: [],
				radiolist1: [{
						name: '发配件',
						key: 'in',
						disabled: false
					},
					{
						name: '退配件',
						key: 'ret',
						disabled: false
					}
				],
				// u-radio-group的v-model绑定的值如果设置为某个radio的name，就会被默认选中
				purchaseType: '发配件',

			};
		},
		computed: {
			factoryOptions() {
				return this.factories.map(factory => ({
					id: factory.userId,
					label: `${factory.userNickName}  (${factory.jobName})`
				}));
			}
		},
		methods: {
			productPartsList() {
			  var that = this;
			  if (!that.isload) {
			    that.$uti.alert('没有更多数据了');
			    return;
			  }
			
			  that.$http.get('productParts/productList', {
			    searchText: that.searchText,
			    pageNo: that.page,
			    pageSize: that.rows
			  }, function(res) {
			    if (res.success) {
			      if (that.page * that.rows < res.data.total) {
			        that.status = 'loadmore';
			        that.page++;
			      } else {
			        that.isload = false;
			        that.status = 'nomore';
			      }
			
			      res.data.items.forEach(item => {
			        const newProduct = that.cloneProducts(item);
			
			        if (Array.isArray(newProduct.accessories)) {
			          newProduct.accessories.forEach(acc => {
			            if (acc.isPartsPublic === 'Y') {
			              that.groups.forEach(g => {
			                g.selectedAccessoriesSave.forEach(sa => {
			                  if (sa.id === acc.id) {
			                    acc.quantity = sa.quantity;
			                    if (!g.selectedAccessories.includes(acc.id)) g.selectedAccessories.push(acc.id);
			                    if (!g.accessoryCheckboxGroup.includes(acc.id)) g.accessoryCheckboxGroup.push(acc.id);
			                  }
			                });
			              });
			            }
			          });
			        }
			
			        that.groups[0].productList.push(newProduct);
			        that.products.push(item);
			      });
			    } else {
			      that.$uti.alert(res.Message);
			      that.isload = false;
			    }
			  });
			},
			factoryList() {
				this.$http.get('factoryUser/list', {

				}, res => {
					if (res.success) {
						this.factories = res.data
						// this.factories = JSON.parse(JSON.stringify(res.data.items))
					}
				})
			},
			getCurrentUserJob() {
				this.$http.get('factoryUser/currentUserJob', {}, res => {
					if (res.success) {
						this.currentUserJob = res.data
					}
				})
			},
			addGroup() {
				const newId = this.groups.length > 0 ? Math.max(...this.groups.map(g => g.id)) + 1 : 1;
				this.groups.push({
					id: newId,
					productList: this.cloneProducts(this.products),
					factoryId: null,
					factory: null,
					searchQuery: '',
					expandedProducts: [],
					productCheckboxGroup: [],
					accessoryCheckboxGroup: [],
					selectedAccessories: [],
					selectedProducts: [],
					selectedAccessoriesSave: [{
						productId: null,
						productName: null,
						productQuantity: 1,
						id: null,
						name: null,
						isPartsPublic : false,
						quantity: 1
					}],
					selectedProductsSave: [{
						id: null,
						name: null,
						quantity: 1
					}],
					collapsed: false
				});
				//重复调用是因为，点击新增组时，会把上个组修改的数量自动带过来
				// this.factoryList()
				// this.productPartsList()
			},
			removeGroup(groupId) {
				this.groups = this.groups.filter(group => group.id !== groupId);
			},
			toggleGroupCollapse(groupId) {
				const group = this.groups.find(g => g.id === groupId);
				if (group) {
					group.collapsed = !group.collapsed;
				}
			},
			// 切换产品展开状态
			toggleProductExpansion(groupId, productId) {
				const group = this.groups.find(g => g.id === groupId);
				if (!group) return;
				// 确保 expandedProducts 数组存在
				if (!group.expandedProducts) {
					this.$set(group, 'expandedProducts', []);
				}

				const index = group.expandedProducts.indexOf(productId);
				if (index === -1) {
					// 展开产品
					group.expandedProducts.push(productId);
				} else {
					// 收起产品
					group.expandedProducts.splice(index, 1);
				}


			},
			showFactoryPicker(groupId) {
				this.currentGroupId = groupId;
				this.showFactoryPickerModel = true;
			},
			factorySelected(e) {

				const index = e.indexs[0]
				const selectedFactory = this.factories[0][index];
				const group = this.groups.find(g => g.id === this.currentGroupId);

				if (group) {
					group.factory = selectedFactory;
					group.factoryId = selectedFactory.userId;
					// // 清空已选择的成品
					// group.selectedProducts = [];
					// group.selectedProductsSave = [];
					// group.selectedAccessories = [];
					// group.selectedAccessoriesSave = [];
				}
				this.showFactoryPickerModel = false;
				this.currentGroupId = null;
			},
			handleCheckboxChange(groupId, productId) {
				this.toggleProductSelection(groupId, productId, null);

			},
			/**
			 * 勾选/取消配件（模板里你是传 accessory.id）
			 * 调用处： @change="handleAccessoriesCheckboxChange(group.id,product.id, accessory.id)"
			 */
			handleAccessoriesCheckboxChange(groupId, productId, accessoryId) {
				const group = this.groups.find(g => g.id === groupId);
				if (!group) return;

				// 找到当前产品/配件对象
				const product = group.productList.find(p => p.id === productId);
				if (!product) return;
				const accessory = product.accessories.find(a => a.id === accessoryId);
				if (!accessory) return;

				// 当前 group 中是否已选中该配件（注意 change 事件触发时，v-model 可能已经更新）
				const isCheckedInThisGroup = (group.selectedAccessories || []).includes(accessoryId);

				// ----- 公共配件：全局同步 -----
				if (accessory.isPartsPublic === 'Y') {
					if (!isCheckedInThisGroup) {
						// 勾选 -> 在所有 group/product 下同步勾选并加入 selectedAccessoriesSave（若不存在则创建）
						this.groups.forEach(g => {
							// 确保 selectedAccessories 数组存在
							if (!Array.isArray(g.selectedAccessories)) this.$set(g, 'selectedAccessories', []);
							if (!g.selectedAccessories.includes(accessoryId)) g.selectedAccessories.push(
								accessoryId);

							// 确保 selectedAccessoriesSave 存在
							if (!Array.isArray(g.selectedAccessoriesSave)) this.$set(g, 'selectedAccessoriesSave',
								[]);

							// 对当前 group 的每个 product，若包含此 accessory，就确保存在一条 save 记录（以 product 为单位）
							g.productList.forEach(p => {
								const targetAcc = p.accessories && p.accessories.find(a => a.id ===
									accessoryId);
								if (!targetAcc) return;
								const exists = g.selectedAccessoriesSave.find(sa => sa.id ===
									accessoryId && sa.productId === p.id);
								if (!exists) {
									g.selectedAccessoriesSave.push({
										productId: p.id,
										productName: p.name,
										isPartsPublic:true,
										productQuantity: p.quantity || 1,
										id: targetAcc.id,
										name: targetAcc.name,
										quantity: targetAcc.quantity || 1
									});
								} else {
									// 保证数量字段与 accessory 保持一致（source 以当前 accessory 为准）
									this.$set(exists, 'quantity', targetAcc.quantity || 1);
								}
								// 同步 UI 中的 accessory.quantity（以当前 targetAcc 为准）
								this.$set(targetAcc, 'quantity', targetAcc.quantity || 1);
							});
						});

					} else {
						// 取消勾选 -> 在所有 groups 中移除该 accessory 的选择 & selectedAccessoriesSave 条目
						this.groups.forEach(g => {
							if (Array.isArray(g.selectedAccessories)) {
								g.selectedAccessories = g.selectedAccessories.filter(id => id !== accessoryId);
							}
							if (Array.isArray(g.selectedAccessoriesSave)) {
								g.selectedAccessoriesSave = g.selectedAccessoriesSave.filter(sa => sa.id !==
									accessoryId);
							}
						});

						// 同时把所有产品列表中该配件的 quantity 恢复到 master（初始）数量
						this.groups.forEach(g => {
							g.productList.forEach(p => {
								p.accessories.forEach(acc => {
									if (acc.id === accessoryId) {
										const masterQty = this.findMasterAccessoryQuantity(p.id,
											acc.id);
										this.$set(acc, 'quantity', masterQty);
									}
								});
							});
						});
					}
					return; // 公共配件处理完毕
				}

				// ----- 非公共配件：只影响当前 group/product -----
				if (!isCheckedInThisGroup) {
					// 勾选：在当前 group 的 selectedAccessoriesSave 中加入一条（若不存在）
					if (!Array.isArray(group.selectedAccessoriesSave)) this.$set(group, 'selectedAccessoriesSave', []);
					// 确保 selectedAccessories 数组存在
					if (!Array.isArray(group.selectedAccessories)) this.$set(group, 'selectedAccessories', []);
					if (!group.selectedAccessories.includes(accessoryId)) group.selectedAccessories.push(
						accessoryId);

					const exists = group.selectedAccessoriesSave.find(sa => sa.id === accessoryId && sa.productId ===
						productId);
					if (!exists) {
						group.selectedAccessoriesSave.push({
							productId: productId,
							productName: product.name,
							productQuantity: product.quantity || 1,
							id: accessory.id,
							isPartsPublic:false,
							name: accessory.name,
							quantity: accessory.quantity || 1
						});
					}
				} else {
					// 取消：仅从本 group 的 selectedAccessories 与 selectedAccessoriesSave 移除对应条目
					group.selectedAccessories = (group.selectedAccessories || []).filter(id => id !== accessoryId);
					if (Array.isArray(group.selectedAccessoriesSave)) {
						group.selectedAccessoriesSave = group.selectedAccessoriesSave.filter(sa => !(sa.id ===
							accessoryId && sa.productId === productId));
					}
					if (Array.isArray(group.selectedAccessories)) {
						group.selectedAccessories = group.selectedAccessories.filter(id => id !== accessoryId);
					}
					// 并把当前 product 下该配件数量恢复到 master（当前 product）
					const masterQty = this.findMasterAccessoryQuantity(productId, accessoryId);
					const accInProduct = product.accessories.find(a => a.id === accessoryId);
					if (accInProduct) this.$set(accInProduct, 'quantity', masterQty);
				}
			},
			// 同步/查找工具：从 this.products 中取某 productId 下 accessoryId 的原始数量
			findMasterAccessoryQuantity(productId, accessoryId) {
				const master = this.products.find(p => p.id === productId);
				if (!master || !master.accessories) return 1;
				const ma = master.accessories.find(a => a.id === accessoryId);
				return (ma && (typeof ma.quantity !== 'undefined')) ? ma.quantity : 1;
			},
			toggleProductSelection(groupId, productId, accessoryId) {
				const group = this.groups.find(g => g.id === groupId);

				if (group) {
					const index = group.selectedProducts.indexOf(productId);
					const productObj = group.productList.find(p => p.id === productId);
					if (index === -1) {
						group.selectedProducts.push(productId);
						const save = {
							id: productId,
							name: productObj.name,
							quantity: 1
						};
						group.selectedProductsSave.push(save);

						group.productCheckboxGroup.push(productId);


					} else {
						productObj.quantity = 1
						group.selectedProducts.splice(index, 1);
						group.selectedProductsSave.splice(index, 1);
						group.productCheckboxGroup.splice(index, 1);

					}
					//子复选框处理
					const product = productObj;


					// 检查成品是否被选中
					const isProductSelected = group.selectedProducts.includes(productId);
					if (isProductSelected) {
						// 成品选中 - 全选所有配件
						//获取所有子元素存入
						const accessoryIds = [];
						try {
							//校验是否存在list
							product.accessories.forEach(item => {
								accessoryIds.push(item.id);
								this.handleAccessoriesCheckboxChange(groupId, productId, item.id)

							});
							group.accessoryCheckboxGroup = [
								...new Set([
									...(group.accessoryCheckboxGroup || []),
									...accessoryIds
								])
							];
						} catch (error) {
							console.error('加载配件失败', error);
							// 可以在这里添加错误处理
						}
					} else {

						// 成品取消 - 取消所有配件
						const accessoryIds = product.accessories.map(a => a.id);
						// 只保留不属于该成品的配件
						group.accessoryCheckboxGroup = (group.accessoryCheckboxGroup || []).filter(
							id => !accessoryIds.includes(id)
						);

						//校验是否存在list
						product.accessories.forEach(item => {
							accessoryIds.push(item.id);
							this.handleAccessoriesCheckboxChange(groupId, productId, item.id)

						});

					}
				}

			},


			// 过滤成品列表：只显示匹配的成品
			filteredProducts(value, group) {
				const that = this;
				that.page = 1;
				const query = group.searchQuery.toLowerCase().trim();

				that.$http.get('productParts/productList', {
					searchText: query,
					pageNo: that.page,
					pageSize: that.rows
				}, function(res) {
					if (res.success) {
						const existingIndex = that.groups.findIndex(item => item.id === group.id);
						that.$set(that.groups[existingIndex], 'productList', res.data.items);
						that.products = [];
						res.data.items.forEach(item => {
							that.products.push(item)
						})
						// res.data.items.forEach(item => {
						// 	//全部展开
						// 	that.toggleProductExpansion(group.id, item.id)

						// });

					} else {
						that.$uti.alert(res.Message);
						// that.isload = false;
						// that.status = 'nomore';
					}
				})


			},


			// 检查成品是否匹配搜索条件
			isProductMatch(product, searchQuery) {
				if (!searchQuery) return false;
				const query = searchQuery.toLowerCase();
				return (
					product.name.toLowerCase().includes(query)
				);
			},

			// 检查配件是否匹配搜索条件
			isAccessoryMatch(accessory, searchQuery) {
				if (!searchQuery) return false;
				const query = searchQuery.toLowerCase();
				return accessory.name.toLowerCase().includes(query);
			},

			//----------------------图片上传

			// 删除图片
			deletePic(event) {
				var that = this;
				that.$http.get('purchaseOrder/deletePictures', {
					fileName: event.file.url
				}, function(res) {

				})
				this[`fileList${event.name}`].splice(event.index, 1);
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file);
				let fileListLen = this[`fileList${event.name}`].length;
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: "uploading",
						message: "上传中",
					});
				});
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i]);
					const response = JSON.parse(result);
					let item = this[`fileList${event.name}`][fileListLen];
					this[`fileList${event.name}`].splice(
						fileListLen,
						1,
						Object.assign(item, {
							status: "success",
							message: "",
							url: response.data,
						})
					);
					fileListLen++;
				}
			},
			uploadFilePromise(file) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: cfg.httpUrl + "purchaseOrder/upload/pictures", // 仅为示例，非真实的接口地址
						filePath: file.url,
						name: "multipartFile",
						formData: {
							'originalName': file.name
						},
						success: (res) => {
							setTimeout(() => {
								resolve(res.data);
							}, 1000);
						},
					});
				});
			},
			// 深拷贝产品数据
			cloneProducts(products) {
				return cloneDeep(products);
			},
			// helper：从 this.products（master 数据）读取某个 product 下 accessory 的“基础/单件数量”
			findMasterAccessoryQuantity(productId, accessoryId) {
				const master = this.products.find(p => p.id === productId);
				if (!master || !Array.isArray(master.accessories)) return 1;
				const ma = master.accessories.find(a => a.id === accessoryId);
				return (ma && typeof ma.quantity !== 'undefined') ? Number(ma.quantity) : 1;
			},

			/**
			 * 当用户调整成品数量（u-number-box）时调用
			 * num: u-number-box 的事件/值（你之前使用 num.value） 
			 * groupId, productId: 当前属于哪个组、哪个成品
			 */
			correctionProduct(num, groupId, productId) {
				const group = this.groups.find(g => g.id === groupId);
				if (!group) return;
				const product = group.productList.find(p => p.id === productId);
				if (!product) return;

				// 兼容 num.value 或 直接数值
				const qty = (typeof num === 'object' && typeof num.value !== 'undefined') ? Number(num.value) : Number(
				num);
				if (Number.isNaN(qty) || qty < 0) return;

				// 更新当前产品数量（UI）
				this.$set(product, 'quantity', qty);

				// 更新当前 group 的 selectedProductsSave（若存在）
				if (Array.isArray(group.selectedProductsSave)) {
					const prodIdx = group.selectedProductsSave.findIndex(item => item.id === productId);
					if (prodIdx !== -1) {
						this.$set(group.selectedProductsSave[prodIdx], 'quantity', qty);
					}
				}

				// 遍历该产品的所有配件，按 master 单位重新计算配件数量并更新
				product.accessories.forEach(acc => {
					const masterUnit = this.findMasterAccessoryQuantity(productId, acc.id); // 单件所需数
					const newAccQty = masterUnit * qty;

					// 更新当前 product 下该配件数量（UI）
					this.$set(acc, 'quantity', newAccQty);

					// 更新当前 group 的 selectedAccessoriesSave（当前 product 下对应配件）
					if (Array.isArray(group.selectedAccessoriesSave)) {
						group.selectedAccessoriesSave.forEach(sa => {
							if (sa.productId === productId && sa.id === acc.id) {
								this.$set(sa, 'quantity', newAccQty);
							}
						});
					}

					// 如果是公共配件 -> 将 newAccQty 同步到所有组 / 所有产品下相同 id 的配件与 selectedAccessoriesSave
					if (acc.isPartsPublic === 'Y') {
						this.groups.forEach(g => {
							// 更新 productList 中对应配件
							g.productList.forEach(p => {
								p.accessories.forEach(acc2 => {
									if (acc2.id === acc.id) {
										this.$set(acc2, 'quantity', newAccQty);
									}
								});
							});

							// 更新 selectedAccessoriesSave 中对应条目
							if (Array.isArray(g.selectedAccessoriesSave)) {
								g.selectedAccessoriesSave.forEach(sa => {
									if (sa.id === acc.id) {
										this.$set(sa, 'quantity', newAccQty);
									}
								});
							}
						});
					}
				});
			},


			// 修改配件数量（模板里你传入的是： @change="(val) => correctionPurchase(val,product.id,accessory,group.id)" ）
			// 参数： num 是 u-number-box 的事件对象/值（你当前使用 num.value），
			// v 是当前 accessory 对象， groupId 表示属于哪个 group
			correctionPurchase(num, productId, v, groupId) {
				const group = this.groups.find(g => g.id === groupId);
				if (!group) return;
				const qty = (typeof num === 'object' && typeof num.value !== 'undefined') ? num.value : num;

				// 更新当前 group.selectedAccessoriesSave 对应条目的 quantity（若存在）
				if (Array.isArray(group.selectedAccessoriesSave)) {
					const existingIndex = group.selectedAccessoriesSave.findIndex(item => item.id === v.id && item
						.productId === productId);
					if (existingIndex !== -1) {
						this.$set(group.selectedAccessoriesSave[existingIndex], 'quantity', qty);
					}
				}

				// 更新当前 productList 中对应 accessory 的数量（找到对应 product）
				const productInGroup = group.productList.find(p => p.id === productId);
				if (productInGroup) {
					const acc = productInGroup.accessories.find(a => a.id === v.id);
					if (acc) this.$set(acc, 'quantity', qty);
				}

				// 如果是公共配件 -> 把数量同步到所有 group.productList 和所有 selectedAccessoriesSave 条目
				if (v.isPartsPublic === 'Y') {
					this.groups.forEach(g => {
						// 更新 selectedAccessoriesSave 条目
						if (Array.isArray(g.selectedAccessoriesSave)) {
							g.selectedAccessoriesSave.forEach(sa => {
								if (sa.id === v.id) {
									this.$set(sa, 'quantity', qty);
								}
							});
						}
						// 更新 productList 中同 id 配件的 quantity
						g.productList.forEach(p => {
							p.accessories.forEach(acc => {
								if (acc.id === v.id) {
									this.$set(acc, 'quantity', qty);
								}
							});
						});
					});
				}
			},
			canvasConfirmHandle(param) {
				this.sign = param;
			},
			openDatePicker() {
				// 打开弹窗
				this.pickerVisible = true;
			},

			// 处理确认（注意不同 uview 版本事件结构可能不同）
			onDateConfirm(e) {
				// 兼容 e.value 或 e.detail.value
				const raw = (e && (e.value || (e.detail && e.detail.value))) || e;
				// raw 可能是时间戳（ms），也可能是一个格式化字符串，根据你 uView 版本而定
				let pickedTs;
				if (typeof raw === 'number') {
					pickedTs = raw;
				} else if (typeof raw === 'string') {
					// 如果是 yyyy-MM-dd 的字符串，构造 Date
					pickedTs = new Date(raw).getTime();
					if (Number.isNaN(pickedTs)) {
						// 尝试把时间戳字符串转成数字
						pickedTs = Number(raw) || Date.now();
					}
				} else {
					// 最保险：如果 e.detail.value 还是 undefined，就用当前时间
					pickedTs = Date.now();
				}

				// 把用户选的日期（年月日）与“当前时分秒”合并
				const pickedDate = new Date(pickedTs);
				const now = new Date();
				pickedDate.setHours(now.getHours(), now.getMinutes(), now.getSeconds(), now.getMilliseconds());

				this.dateValue = pickedDate.getTime();
				this.displayDate = this.formatDateTime(pickedDate);

				// 关闭 picker
				this.pickerVisible = false;
			},

			onDateCancel() {
				this.pickerVisible = false;
			},

			formatDateTime(d) {
				const pad = (n) => String(n).padStart(2, '0');
				return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())} ` +
					`${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
			},
			//提交表单
			submitPurchase() {
				console.log("groups-----", this.groups)
				if (this.groups[0].factoryId == null) {
					this.$uti.alert('请选择下发工厂')
					return
				}
				const factories = this.groups.map(item => {
				  const uniquePartsMap = new Map();
				
				  item.selectedAccessoriesSave.forEach(part => {
				    if (uniquePartsMap.has(part.id)) {
				      // 已存在，标记为公共配件
				      uniquePartsMap.set(part.id, {
				        ...part,
				        productId: -1,
				        productName: '公共配件' // 或你希望的名字
				      });
				    } else {
				      uniquePartsMap.set(part.id, { ...part });
				    }
				  });
				
				  const uniqueParts = Array.from(uniquePartsMap.values());
				
				  return {
				    factoryId: item.factory.userId,
				    products: item.selectedProductsSave,
				    parts: uniqueParts
				  };
				});


				const fc = factories[0];

				if (factories.length <= 0 || fc.parts.length <= 0) {
					this.$uti.alert('请选择成品或配件')
					return
				}
				const productProcessingPriceArr = [];

				if (this.groups[0].factory.jobId === 19 || this.groups[0].factory.jobId === 18) {
					fc.parts.forEach(part => {
						const match = this.groups[0].productList.find(p => p.id === part.productId);
						if (match) {
							// 判断是否已存在，避免重复
							if (!productProcessingPriceArr.some(item => item.productId === part.productId)) {
								productProcessingPriceArr.push({
									productId: part.productId,
									productProcessingPrice: match.productProcessingPrice
								});
							}
						}
					});


				}

				if (this.currentUserJob != 'cg') {
					const lines = [];
					fc.parts.forEach(item => {
						const oAcc = this.groups[0].productList.find(op => op.id === item.productId && op.name ===
								item.productName)
							.accessories.find(op => op.id === item.id && op.name === item.name);

						if (oAcc && oAcc.stockNum) {
							if (item.quantity > oAcc.stockNum) {
								lines.push(item.productName + '-' + item.name + ' 库存不足')

							}
						} else {
							lines.push(item.productName + '-' + item.name + ' 库存不足')
						}

					});

					if (lines.length > 0) {
						uni.showModal({
							title: '异常',
							showCancel: false,
							confirmText: '关闭',
							content: lines.join('\n'), // 换行生效
							success: (res) => {}
						});

						// this.$uti.alert(lines.join('\n'));
						return;

					}

				}

				if (!this.purchaseType) {
					this.$uti.alert('请选择采购类型')
					return
				}
				if (this.currentUserJob != 'cg') {
					if (!this.remark) {
						this.$uti.alert('请填写备注')
						return
					}
					if (this.fileList1.length <= 0) {
						this.$uti.alert('请上传单据')
						return
					}

				}

				if (!this.sign) {
					this.$uti.alert('请输入并确认签名')
					return
				}

				let pt = '';
				if (this.purchaseType === '发配件') {
					pt = 'in'
				} else {
					pt = 'ret'
				}

				let param = {
					factories: factories,
					purchaseNo: this.wareNum,
					purchaseType: pt,
					productDetails: productProcessingPriceArr,
					remark: this.remark,

					createTime: this.displayDate,
					images: this.fileList1,
					sign: this.sign,
					msg: this.remark
				}

				console.log("create param", param)


				this.$http.post('purchaseOrder/create', param, res => {
					if (res.success) {
						this.$uti.alert('下单成功')

						this.groups = [{
							id: 1,
							//工厂
							factoryId: null,
							factory: null,
							searchQuery: '',
							productList: [],
							expandedProducts: [],
							productCheckboxGroup: [],
							accessoryCheckboxGroup: [],
							//选中的配件
							selectedAccessories: [],
							//选中的成品
							selectedProducts: [],
							selectedAccessoriesSave: [],
							selectedProductsSave: [],
							collapsed: false
						}]
						this.wareNum = '';
						this.purchaseType = '';
						this.remark = '';
						this.fileList1 = [];
						this.sign = '';
						this.remark = '';

						uni.navigateTo({
							url: `/cmhqPage/purchaseList/purchaseList?type=toAudit`
						})
					} else {
						this.$uti.alert(res.message)
					}
					this.orderLoading = false
				})



			}
		}
	};
</script>

<style lang="scss">
	* {
		margin: 0;
		padding: 0;
		box-sizing: border-box;

		font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
	}

	page {
		background: linear-gradient(135deg, #f5f7fa 0%, #e4edf5 100%);
		padding: 20px;
		box-sizing: border-box
	}

	.container {
		margin: 0 auto;
	}

	.header {
		text-align: center;
		padding: 30px 0;
		color: #2c3e50;
	}

	.header h1 {
		font-size: 32px;
		margin-bottom: 10px;
		font-weight: 600;
		background: linear-gradient(90deg, #3498db, #2ecc71);
		-webkit-background-clip: text;
		-webkit-text-fill-color: transparent;
	}

	.header p {
		font-size: 16px;
		color: #7f8c8d;
		max-width: 600px;
		margin: 0 auto;
		line-height: 1.6;
	}

	.group-container {
		background: white;
		border-radius: 16px;
		box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
		overflow: hidden;
		margin-bottom: 25px;
		transition: all 0.3s ease;
	}

	.group-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20px 25px;
		background: linear-gradient(90deg, #3498db, #2ecc71);
		color: white;
		cursor: pointer;
	}

	.group-title {
		display: flex;
		align-items: center;
		gap: 12px;
		font-size: 20px;
		font-weight: 600;
	}

	.group-actions {
		display: flex;
		gap: 15px;
	}

	.action-btn {
		background: rgba(255, 255, 255, 0.2);
		border: none;
		width: 36px;
		height: 36px;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		cursor: pointer;
		color: white;
		font-size: 18px;
		transition: all 0.3s;
	}

	.action-btn:hover {
		background: rgba(255, 255, 255, 0.3);
		transform: scale(1.05);
	}

	.delete-btn {
		background: rgba(231, 76, 60, 0.8);
	}

	.group-content {
		padding: 25px;
	}

	.form-section {}

	.section-title {
		font-size: 18px;
		font-weight: 600;
		color: #2c3e50;
		margin-bottom: 15px;
		padding-bottom: 10px;
		border-bottom: 1px solid #eee;
		display: flex;
		align-items: center;
		gap: 8px;
	}

	.search-container {
		position: relative;
		margin-bottom: 20px;
	}

	.search-input {
		width: 100%;
		padding: 14px 20px 14px 45px;
		border: 1px solid #dcdfe6;
		border-radius: 12px;
		font-size: 16px;
		transition: all 0.3s;
		background: #f8f9fa;
	}

	.search-input:focus {
		outline: none;
		border-color: #3498db;
		box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.2);
		background: white;
	}

	.search-icon {
		position: absolute;
		left: 15px;
		top: 50%;
		transform: translateY(-50%);
		color: #95a5a6;
		font-size: 18px;
	}

	.products-container {
		max-height: 500px;
		overflow-y: auto;
		padding-right: 10px;
	}

	.product-item {
		border: 1px solid #eee;
		border-radius: 12px;
		margin-bottom: 15px;
		overflow: hidden;
		transition: all 0.3s;
	}

	.u-checkbox-group {
		flex-direction: column;
	}

	.product-item.active {
		border-color: #3498db;
		box-shadow: 0 5px 15px rgba(52, 152, 219, 0.15);
	}

	.product-header {
		display: flex;
		align-items: center;
		padding: 15px 20px;
		background: #f8fafc;
		cursor: pointer;
	}

	.product-checkbox {
		margin-right: 15px;
		width: 20px;
		height: 20px;
		accent-color: #3498db;
	}

	.product-info {
		flex: 1;
	}

	.product-name {
		font-size: 17px;
		font-weight: 600;
		color: #2c3e50;
	}

	.product-id {
		font-size: 14px;
		color: #7f8c8d;
		margin-top: 4px;
	}

	.product-arrow {
		font-size: 18px;
		color: #95a5a6;
		transition: transform 0.3s;
	}

	.product-arrow.down {
		transform: rotate(90deg);
	}

	.accessories-container {
		background: white;
		padding: 15px 20px;
		border-top: 1px solid #eee;
		display: grid;
		grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
		gap: 15px;
	}

	.accessory-item {
		display: flex;
		align-items: center;
		padding: 12px 15px;
		background: #f8fafc;
		border-radius: 10px;
		border: 1px solid #eee;
	}

	.accessory-info {
		flex: 1;
	}

	.accessory-name {
		font-weight: 600;
		color: #34495e;
		margin-bottom: 5px;
	}

	.accessory-spec {
		font-size: 13px;
		color: #7f8c8d;
	}

	.quantity-control {
		display: flex;
		align-items: center;
		gap: 8px;
	}

	.quantity-btn {
		width: 32px;
		height: 32px;
		border-radius: 8px;
		border: 1px solid #dcdfe6;
		background: white;
		font-size: 16px;
		display: flex;
		align-items: center;
		justify-content: center;
		cursor: pointer;
		transition: all 0.2s;
	}

	.quantity-btn:hover {
		background: #f1f8ff;
		border-color: #3498db;
		color: #3498db;
	}

	.quantity-input {
		width: 60px;
		text-align: center;
		padding: 8px;
		border: 1px solid #dcdfe6;
		border-radius: 8px;
		font-size: 16px;
	}

	.quantity-input:focus {
		outline: none;
		border-color: #3498db;
	}

	.add-group-btn {
		display: flex;
		justify-content: center;
		margin: 20px 0;
	}

	.btn-primary {
		background: linear-gradient(90deg, #3498db, #2ecc71);
		color: white;
		border: none;
		padding: 14px 35px;
		font-size: 18px;
		font-weight: 600;
		border-radius: 12px;
		cursor: pointer;
		display: flex;
		align-items: center;
		gap: 10px;
		transition: all 0.3s;
		box-shadow: 0 5px 15px rgba(52, 152, 219, 0.3);
	}

	.btn-primary:hover {
		transform: translateY(-3px);
		box-shadow: 0 8px 20px rgba(52, 152, 219, 0.4);
	}

	.btn-primary:active {
		transform: translateY(1px);
	}

	.empty-state {
		text-align: center;
		padding: 40px 20px;
		color: #95a5a6;
		background: #f8fafc;
		border-radius: 12px;
		border: 2px dashed #e0e7ff;
	}

	.empty-state i {
		font-size: 48px;
		margin-bottom: 15px;
		color: #bdc3c7;
	}

	.empty-state p {
		font-size: 16px;
		margin-top: 10px;
	}

	.footer {
		text-align: center;
		padding: 10px 0;
		color: #7f8c8d;
		font-size: 14px;
		border-top: 1px solid #eee;
		margin-top: 20px;
	}

	/* 自定义滚动条 */
	::-webkit-scrollbar {
		width: 8px;
	}

	::-webkit-scrollbar-track {
		background: #f1f1f1;
		border-radius: 4px;
	}

	::-webkit-scrollbar-thumb {
		background: #c5d9e8;
		border-radius: 4px;
	}

	::-webkit-scrollbar-thumb:hover {
		background: #3498db;
	}

	@media (max-width: 768px) {
		.group-content {
			padding: 15px;
		}

		.accessories-container {
			grid-template-columns: 1fr;
		}
	}


	.signature-container {
		padding: 20rpx;
	}

	.canvas {
		width: 100%;
		height: 400rpx;
		background-color: #f9f9f9;
		border: 1px solid #eee;
		border-radius: 8rpx;
	}

	.btn-group {
		margin-top: 40rpx;
		display: flex;
		justify-content: space-between;
	}



	.title {
		height: 50upx;
		line-height: 50upx;
		font-size: 16px;
	}

	.mycanvas {
		width: 100%;
		height: 200px;
		background-color: #ECECEC;
	}

	.footer {
		font-size: 16px;
		display: flex;
		justify-content: space-around;
		align-items: center;
		margin-top: 0;
	}

	.left,
	.right {
		line-height: 30px;
		height: 30px;
		width: 80px;
		text-align: center;
		font-weight: bold;
		color: white;
		border-radius: 5upx;
	}

	.left {
		background: #007AFF;
	}

	.right {
		background: orange;
	}

	.date-box {
		padding: 10px;
		border: 1px solid #ccc;
		border-radius: 4px;
		color: #333;
	}
</style>